package com.bhh.bio;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Socket;

/**
 * @author bhh
 * @description 基于BIO模型, 客户端实现
 * 和 UserInputHandler类
 * 和 ChatServer 类 + ChatHandler类配合使用
 *
 * @date Created in 2021-04-07 16:48
 * @modified By
 */
@Slf4j
public class ChatClient {
    private final String SERVER_IP = "127.0.0.1";
    private final int SERVER_PORT = 8888;
    private final String QUIT = "quit";
    public boolean toQuit = false;

    private Socket socket;
    private BufferedWriter writer;
    private BufferedReader reader;

    /**
     * 发送消息到服务器
     *
     * @param msg
     */
    public void send(String msg) throws IOException {
        // 判断关于socket的输出流是否被关闭
        if (!socket.isOutputShutdown()) {
            writer.write(msg);
            writer.flush();
        }
    }

    /**
     * 获取服务器信息
     *
     * @return
     * @throws IOException
     */
    public String get() throws IOException {
        String msg = null;
        if (!socket.isInputShutdown()) {
            msg = reader.readLine();
        }
        return msg;
    }

    /**
     * 客户端断开连接
     *
     * @param msg
     * @return
     */
    public boolean quit(String msg) {
        return QUIT.equals(msg);
    }

    /**
     * writer流关闭, 若是关闭socket中的任一流, socket流与socket有关的流都会关闭
     *
     * @param writer
     */
    private void close(Writer writer) {
        try {
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 整合各个封装的方法完成功能
     */
    public void start() {

        try {
            socket = new Socket(SERVER_IP, SERVER_PORT);
            writer = new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())
            );
            reader = new BufferedReader(
                    new InputStreamReader(socket.getInputStream())
            );

            // 获取控制台的输入, 并发送信息
            new Thread(new UserInputHandler(this)).start();

            // 获取服务器回复信息
            String fwdMsg = null;
            while ((fwdMsg = get()) != null) {
                log.info(fwdMsg);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(writer);
        }
    }

    public static void main(String[] args) {
        ChatClient client = new ChatClient();
        client.start();
    }
}
